<template>
<div class="submit-wrap">
    <G_header title="提交订单" />
    <div style="padding: .25rem"></div>
    <van-contact-card type="edit" :name="this.global.state.defaultAddress.realname" :tel="this.global.state.defaultAddress.mobile" @click="editAdd" />
    <div v-if="!type">
        <van-card :num="goods.number" :price="goods.price" :title="goods.title" :thumb="goods.avatar">
            <div class="goods-num" slot="num">
                <van-stepper v-model="from.goodsNumber" />
            </div>
        </van-card>
        <van-cell-group>
            <van-cell title="商品金额" :value="goods.price" />
            <van-cell title="小计" :value="((goods.price *10 )* (from.goodsNumber *10)) / 100" />
        </van-cell-group>
    <van-cell-group>
        <van-field v-model="from.remark" placeholder="备注" />
    </van-cell-group>
    <div class="submit">
        <van-button type="danger" block @click="show = true">确定提交</van-button>
    </div>
    </div>
    <div v-else>
        <van-card :num="goods.number" :title="goods.title" :thumb="goods.avatar">
            <div slot="price">
                <span class="integral">{{ goods.integral }} 积分 </span>
            </div>
            <div class="goods-num" slot="num">
                <van-stepper v-model="from.goodsNumber" />
            </div>
            
        </van-card>
        <div class="submit">
        <van-button type="danger" block @click="exchange">兑换</van-button>
    </div>
    </div>
    <van-popup v-model="show" :style="{ height:'40%' }" position="bottom">
        <van-cell-group title="选择支付方式">
            <van-cell title="微信支付" is-link @click="pay('1')" />
            <van-cell title="余额支付" is-link @click="pay('2')" />
        </van-cell-group>
    </van-popup>
</div>
</template>

<script>
import {
    Notify,
    ContactCard,
    Toast,
    Dialog
} from 'vant';
import axios from 'axios'
import wx from 'weixin-js-sdk'
import pay from "@/views/utils/pay";
export default {
    name: 'Submit',
    data() {
        return {
            chosenAddressId: '1',
            show: false,
            radio: '1',
            AreaList: null,
            goods: [],
            store: [],
            total_price: null,
            addressData: null,
            from: {
                goodsNumber: 1,
                remark: '',
                dispatch_price: '',
                coupons_price: ''
            },
            defaultAddress: '',
            type: null
        }
    },
    watch: {

    },
    computed: {
        
    },
    mounted() {
        this.type = this.$route.query.type;
        let defaultAddress = this.global.state.defaultAddress;
        if (!defaultAddress) {
            Dialog.alert({
                title: '提示',
                message: '你没有填写收货地址,快去填写地址吧'
            }).then(() => {
                this.$router.push({
                    name: 'addressAddressList',
                    path: '../addressList',
                    query: {
                        type: 'add'
                    }
                });
            });
        }
        this.addressData = this.global.state.addressData || {};
        this.from.goodsNumber = this.global.state.singleGoods.number;
        this.goods = this.global.state.singleGoods;
        if(this.$route.query.good){
            this.goods.title = this.goods.title + '(' +  this.global.state.BuyGoodsData.selectedSkuComb.s0 + this.global.state.BuyGoodsData.selectedSkuComb.s1 + ')'
            this.goods.price = this.global.state.BuyGoodsData.selectedSkuComb.price / 100;
        }
        this.store = this.$route.params.store;
    },
    methods: {
        editAdd() {
            this.$router.push({
                path: '../address/list',
                name: 'addressList'
            })
        },
        pay(e) {
            this.global.state.BuyGoodsData.selectedNum = this.from.goodsNumber;
            let address = this.global.state.defaultAddress;
            let goods = this.global.state.singleGoods;
            goods.number = this.from.goodsNumber;
            let store_id = goods.store_id;
            goods.store = null;
            goods.remark = null;
            goods.address = address;
            goods.type = null;
            let goodsData = JSON.stringify(goods);
            let params = {};
            params.token = this.global.state.accessToken;
            if(this.$route.query.good){
                goods.spec_price.forEach(item=>{
                    if(item.id == this.global.state.BuyGoodsData.selectedSkuComb.id){
                        goods.params = item;
                    }
                })
                params.price = this.global.state.BuyGoodsData.selectedSkuComb.price / 100 + Number(goods.pack_price);
            }else {
                axios.get(`/api/store/merchant/is_member/${store_id}`,{params}).then(res=>{
                        params.price = (this.goods.member_price * 10) * (this.from.goodsNumber * 10) + Number(goods.pack_price);
                        params.price = params.price / 100;
                }).catch(err=>{
                    if(err.response.status == 403){
                        params.price = (this.goods.price * 10) * (this.from.goodsNumber * 10) + Number(goods.pack_price);
                        params.price = params.price / 100;
                    }
                })
                
            }
            params.box_price = 0;
            params.address_id = address.id;
            params.dispatch_price = 0;
            params.remark = this.from.remark;
            params.params = goodsData;
            
            if (e == 1) {
                params.pay_mode = 'wechat';
            } else {
                params.pay_mode = '';
            }
            let loa = true;
            Toast.loading({
                mask: loa,
                message: '加载中...'
            });
            this.axios.post('/api/store/user/order/create/' + store_id, params).then(res => {
                if (e == 1) {
                    this.wxPay(res.data.data);
                } else {
                    Notify({
                        type: 'primary',
                        background: "#07c160",
                        message: res.data.message,
                        onClose: () => {
                            this.$router.push({
                                name: 'order',
                                params: {
                                    index: 2
                                }
                            })
                        }
                    });
                }
            }).catch(err => {
                console.log(err)
            })
            this.show = false;
        },
        exchange(){
            let address = this.global.state.defaultAddress;
            let goods = this.global.state.singleGoods;
            goods.number = this.from.goodsNumber;
            let store_id = goods.store_id;
            goods.store = null;
            goods.remark = null;
            goods.address = address;
            let goodsData = JSON.stringify(goods);
            let params = {};
            params.token = this.global.state.accessToken;
            let integral = (this.goods.integral * 10) * (this.from.goodsNumber * 10);
            params.integral = integral / 100;
            params.box_price = 0;
            params.address_id = address.id;
            params.dispatch_price = 0;
            params.remark = this.from.remark;
            params.params = goodsData;
            params.pay_mode = 'integral';
            let loa = true;
            Toast.loading({
                mask: loa,
                message: '加载中...',
                duration: 0, // 持续展示 toast
            });
            this.axios.post('/api/store/user/order/create/' + store_id, params).then(res => {
            Notify({
                type: 'primary',
                background: "#07c160",
                message: res.data.message,
                onClose: () => {
                    this.$router.push({
                        name: 'order',
                        params: {
                            index: 2
                        }
                    })
                }
                })

            }).catch(err => {
                console.log(err)
            })
        },
        wxPay(data) {
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: data.appId, // 必填，公众号的唯一标识
                timestamp: data.timestamp, // 必填，生成签名的时间戳
                nonceStr: data.nonceStr, // 必填，生成签名的随机串
                signature: data.signature, // 必填，签名，见附录1
                jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            });
            wx.ready(function () {
                wx.chooseWXPay({
                    timestamp: data.timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                    nonceStr: data.nonceStr, // 支付签名随机串，不长于 32 位
                    package: data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                    signType: 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                    paySign: data.paySign, // 支付签名
                    success: function (res) {
                        // 支付成功后的回调函数
                        if (res.errMsg == "chooseWXPay:ok") {
                            Dialog({
                                message: '支付成功'
                            });
                        } else {
                            Dialog({
                                message: '错误'
                            });
                        }
                    },
                    error: function () {
                        Dialog({
                            message: '支付失败'
                        });
                    },
                    cancel: function () {
                        Dialog({
                            message: '取消支付'
                        });
                    }
                });
            });
        }
    },
    components: {
        ContactCard
    }
}
</script>

<style lang="less" scoped>
.submit-wrap {
    .submit {
        padding: 10px 15px;
    }
}
.goods-num {
    position: absolute;
    bottom: 0;
    right: 0;
}
.address {
    padding: 16px;
    background-color: white;
    .l {
        width: 90%;
        p {
            margin: .1rem 0;
        }
    }

    .r {
        width: 10%;
        text-align: center;
        display: flex;
        justify-items: center;
        align-items: center;

        i {
            margin: 5px 0;
        }
    }
}

.address::before {
    position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
    height: 2px;
    background: -webkit-repeating-linear-gradient(135deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
    background: repeating-linear-gradient(-45deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
    background-size: 80px;
    content: '';
}
.integral {
  color: #ff8140;
  font-size: 1rem;
}
</style>
